//
//  IMGroupCreateAddMemberView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/7/14.
//

import UIKit
import Reusable
import Kingfisher

extension IMGroupCreateAddMemberView: NibLoadable {}

class IMGroupCreateAddMemberView: UIView {
    
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var searchButton: UIButton!
    
    @IBOutlet weak var markView: UIView!
    @IBOutlet weak var avatartImageView: UIImageView!
    @IBOutlet weak var nicknameLabel: UILabel!
    @IBOutlet weak var selectedButton: UIButton!
    
    var closeHandler: (() -> Void)?
    var didSelectedHandler: ((UserModel) -> Void)?
    
    var resultModel: UserModel? {
        didSet {
            guard let model = resultModel else {
                markView.isHidden = true
                return
            }
            
            markView.isHidden = model.id == 0
            avatartImageView.kf.setImage(with: URL(string: model.avatar))
            nicknameLabel.text = model.username
            //LanguageManager.currentLanguageToText(model.username, model.usernameRu)
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        markView.isHidden = true
        avatartImageView.addRoundedCorners(radius: 22.5)
        selectedButton.addRoundedCorners(radius: 18)
        
        size = CGSizeMake(xScreenW, xScreenH*2.0/3.0)
        addRoundedCorners(radius: 24)
        searchTextField.delegate = self
        searchTextField.becomeFirstResponder()
        
        updateLanguageAction()
    }
    
    @IBAction func closeAction(_ sender: Any) {
        closeHandler?()
    }
    
    @IBAction func searchAction(_ sender: Any) {
        endEditing(true)
        
        if searchTextField.text!.isEmpty {
            YLHUD.showMessage("请输入用户 ID".localized(.call))
            return
        }
        
        ZIMKitCore.shared.queryUserInfo(by: searchTextField.text!) { userInfo, error in
            xLog("code: \(error.code), message: \(error.message)")
            xLog("用户信息 \(userInfo?.id ?? "")")
            xLog("用户信息 \(userInfo?.name ?? "")")
            xLog("用户信息 \(userInfo?.avatarUrl ?? "")")
            
            guard let model = userInfo else {
                YLHUD.showMessage("请输入正确的用户 ID".localized(.call))
                return
            }
            if error.code.rawValue != 0 {
                YLHUD.showMessage("请输入正确的用户 ID".localized(.call))
                return
            }
            let userModel = UserModel()
            userModel.id = model.id.sg.toInt
            userModel.username = model.name
            userModel.avatar = model.avatarUrl ?? ""
            self.resultModel = userModel
        }
        
        
//        YLHUD.showLottie()
//        let target = LoginAPI.userInfo(searchTextField.text!)
//        YLRequest.request(target) { result in
//            switch result {
//            case .success(let res):
//                let dataDictionary = res.dataDictionary["data"] as! [String : Any]
//                
//                if let model = JsonUtil.modelFromDictionary(dataDictionary, UserModel.self) {
//                    if model.id > 0 {
//                        YLHUD.hideHUD()
//                        self.resultModel = model
//                        return
//                    }
//                }
//                
//                YLHUD.showMessage("请输入正确的用户 ID")
//                
//            case .failure(let err):
//                self.resultModel = nil
//                YLHUD.showHint(.error, err.errMsg)
//            }
//        }
    }
    
    @IBAction func didSelectedAction(_ sender: UIButton) {
        guard let model = resultModel else { return }
        
        if model.id == UserProfile.userId {
            YLHUD.showMessage("无法添加自己为群成员".localized(.call))
            return
        }
        
        didSelectedHandler?(model)
    }
    
    func updateLanguageAction() {
        titleLabel.text = "添加群成员".localized(.call)
        searchTextField.placeholder = "请输入用户 ID".localized(.call)
        searchButton.setTitle("搜索".localized(.call), for: .normal)
        selectedButton.setTitle("选择".localized(.call), for: .normal)
    }
}

extension IMGroupCreateAddMemberView: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "" {
            return true
        }
        
        if "0123456789".contains(string) {
            return true
        }
        
        return false
    }
}
